package com.chenyun.tenant;

import com.chenyun.common.context.UserContextHolder;
import com.chenyun.common.utils.StringUtils;
import com.chenyun.common.vo.SessionUser;

import java.io.Serializable;

/**
 * TenantContext：
 * Description:
 *
 * @author: Lonni
 * @date: 2023/12/13 0013 10:52
 */
public class TenantContext implements Serializable {
    public static final TenantContext me = new TenantContext();

    private static final ThreadLocal<String> tenantIdLocal = new InheritableThreadLocal<>();


    private static final ThreadLocal<Boolean> IgnoreTenantLocal = new InheritableThreadLocal<>();


    public void setTenantId(String tid) {
        tenantIdLocal.set(tid);
    }

    public void setIgnoreTenant(Boolean ig) {
        IgnoreTenantLocal.set(ig);
    }

    public String tenantId() {
        String tenantId = tenantIdLocal.get();
        if (StringUtils.isNotBlank(tenantId)) {
            return tenantId;
        }
        //不存在 去用户上下文
        SessionUser user = UserContextHolder.getUser();
        if (user != null) {
            return user.getClientId();
        }
        return null;
    }

    /**
     * 是否忽略租户
     *
     * @return
     */
    public Boolean ignore() {
        Boolean aBoolean = IgnoreTenantLocal.get();
        if (aBoolean == null) {
            return Boolean.FALSE;
        }
        return aBoolean;
    }


    public void clear() {
        tenantIdLocal.remove();
        IgnoreTenantLocal.remove();
    }


}



